package com.tjcu.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/10/12 9:52
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:
 */
public class MybatisUtil {
    /**
     * 线程绑定对象，保证是同一个对象
     */
    private static final ThreadLocal<SqlSession> t1 = new ThreadLocal<>();
    private static SqlSessionFactory factory;

    static {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        factory = new SqlSessionFactoryBuilder().build(is);
    }

    /**
     * 创建SqlSession
     *
     * @return sqlSession
     */
    private static SqlSession openSession() {
        SqlSession sqlSession = t1.get();
        if (sqlSession == null) {
            sqlSession = factory.openSession();
            t1.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 调用功能方法
     *
     * @param clazz
     * @return Object
     */
public  static Object getMapper(Class clazz) {
        return openSession().getMapper(clazz);
    }

    /**
     * 关闭资源
     */
    public static void close() {
        if (openSession() != null) {
            openSession().close();
        }
        t1.remove();
    }

    /**
     * 提交事务,关闭资源
     */
    public static void commit() {
        //1、提交事务
       openSession().commit();
        //2、关闭资源
        close();
        t1.remove();
    }

    /**
     * 回滚事务,关闭资源
     */
    public static void rollback() {
        //1、提交事务
        openSession().rollback();
        //2、关闭资源
        close();
        t1.remove();
    }


}
